package com.sy.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.sy.constant.PayConstant;
import com.sy.context.BaseContext;
import com.sy.pojo.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliPayServiceImpl implements AliPayService {
    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrdersService ordersService;

    /**
     * 生成支付宝支付二维码
     * @param orders 订单对象（订单编号  订单金额）
     * @param courseName  课程名称
     * @return
     */
    @Override
    public Map createNative(Orders orders, String courseName) {
        Map<String, String> map = new HashMap<String, String>();
        //创建预下单请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //对结果精度要求高，使用：BigDecimal四舍五入并保留两位有效数字
        BigDecimal bigDecimal = BigDecimal.valueOf(orders.getAmount());
        //RoundingMode可指定多种去尾规则
        BigDecimal money = bigDecimal.setScale(2, RoundingMode.HALF_UP);//四舍五入后并保留两位小数
        System.out.println("预下单金额:" + money.doubleValue());
        System.out.println("订单号:" + orders.getNumber());
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orders.getNumber() + "\"," +
                "    \"total_amount\":\"" + money.doubleValue() + "\"," +
                "    \"subject\":\""+courseName+"\"," +
                "    \"store_id\":\"xa_001\"," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数
        //发出预下单业务请求
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            //从响应对象获取响应状态码
            String code = response.getCode();
            System.out.println("响应码:" + code);
            //全部的响应结果
            String body = response.getBody();
            System.out.println("返回结果:" + body);

            if (code.equals("10000")) {
                //response.getQrCode():获取生成二维码的url
                map.put("qrcode", response.getQrCode());
                //response.getOutTradeNo()：获取订单编号
                map.put("out_trade_no", response.getOutTradeNo());
                map.put("total_fee", money + "");
                map.put("code", 1 + "");
                //将与下单信息保存到订单表中
                //设置当前订单的用户id
                orders.setUserId(BaseContext.getCurrentId());
                //设置生成的订单时间
                orders.setOrderTime(LocalDateTime.now());
                //设置支付状态
                orders.setPayStatus(PayConstant.PAY_NOPAY);
                //把预下单的订单信息保存到数据库
                ordersService.save(orders);
            } else {
                map.put("code", 0 + "");
                System.out.println("预下单接口调用失败:" + body);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 交易查询接口alipay.trade.query：
     * 获取指定订单编号的，交易状态
     * @throws AlipayApiException
     */
    @Override
    public Map<String, String> queryPayStatus(String out_trade_no) {
        Map<String, String> map = new HashMap<String, String>();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + out_trade_no + "\"," +
                "    \"trade_no\":\"\"}"); //设置业务参数
        //发出请求
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            String code = response.getCode();
            System.out.println("返回值1:" + response.getBody());
            if (code.equals("10000")) {
                //System.out.println("返回值2:"+response.getBody());
                //商户订单号
                map.put("out_trade_no", out_trade_no);
                //交易状态
                map.put("tradestatus", response.getTradeStatus());
                //支付宝交易号
                map.put("trade_no", response.getTradeNo());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }
}
